package com.woniu.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisUtil;
import com.woniu.model.dto.CoachDto;
import com.woniu.model.dto.VenueDto;
import com.woniu.model.entity.YUser;
import com.woniu.model.entity.YVenue;
import com.woniu.model.form.*;
import com.woniu.model.param.*;
import com.woniu.service.YVenueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡歌
 * @since 2024年05月22日
 */
@RestController
@RequestMapping("/yVenue")
@Api(tags = "场馆操作信息的一些接口")
public class YVenueController {

    @Resource
    private YVenueService venueService;
    @Resource
    private RedisUtil redisUtil;

    /**
     *
     * @param mobile 场馆发送注册短信
     * @return
     */
    @GetMapping("/venueRegisterSendMessage")
    @ApiOperation(value = "场馆注册发送短信")
    public Result<?> venueRegisterSendMessage(@RequestParam("mobile")String mobile){
        venueService.venueRegisterCode(mobile);
        return Result.newInstance(null).setMsg("发送注册验证码成功").setCode(200);
    }

    /**
     *
     * @param form 场馆短信注册账号
     * @return
     * @throws Exception
     */
    @PostMapping("/venueRegister")
    @ApiOperation(value = "场馆账户短信注册")
    public Result<?> venueRegister(@RequestBody VenueRegisterForm form)throws Exception{
        venueService.CodeRegister(BeanUtil.toBean(form, VenueRegisterParam.class));
        return Result.newInstance(null).setCode(200).setMsg("注册成功");
    }


    /**
     *
     * @param form 场馆账号密码登录
     * @param response
     * @return 返回整个登录成功的场馆
     * @throws Exception 当场馆密码或者账号出现错误时 抛出异常
     */
    @PostMapping("/venueLogin")
    @ApiOperation(value = "场馆账号密码登录的接口")
    public Result venueLogin(@RequestBody venueLoginForm form, HttpServletResponse response) throws    Exception{

        VenueDto dto = venueService.venueLogin(BeanUtil.toBean(form, venueLoginParam.class));

        Map<String, Object> map = BeanUtil.beanToMap(dto);
        HashMap<String, Object> acccessBoby = new HashMap<>();
        String random = new Snowflake(1, 1).nextIdStr();//雪花算法，生成一个随机值，确保不同的短token不一致
        acccessBoby.put("random",random);

        String accessToken = JwtUtil.createToken(acccessBoby, 15);//生成一个短token
        String refreshToken = JwtUtil.createToken(map, 3*24*60);//生成一个长token
        //将长token保存到redis
        redisUtil.set(accessToken,refreshToken,3*24*60*60);
        //响应token给前端
        response.setHeader("token", accessToken);
        response.setHeader("Access-Control-Expose-Headers", "token");
        return Result.newInstance(VenueDto.class).setData(dto).setMsg("登录成功");
    }

    /**
     *
     * @param form 修改场馆信息  传入需要修改的参数
     * @return 返回修改后的场馆对象
     */
    @ApiOperation("修改场馆名和介绍")
    @GetMapping("/updateVenue")
    public Result<VenueDto> updateVenue(@RequestBody AdminUpdateVenueForm form){
        AdminUpdateVenueParam param = BeanUtil.toBean(form, AdminUpdateVenueParam.class);
        YVenue venue = venueService.updateVenue(param);
        return Result.newInstance(VenueDto.class).setData(BeanUtil.toBean(venue,VenueDto.class));
    }


    /**
     *form 修改场馆状态 参数场馆ID 以及要修改的状态值
     * @param
     * @return
     */
    @GetMapping("/updateVenueState")
    @Transactional
    @ApiOperation("修改场馆状态0 已注销 1未认证 2认证成功 3认证失败'")
    public Result updateVenueState(UpdateVenueStateParam param){
        venueService.updateVenueState(param);
        return Result.getResult().setMsg("修改状态成功");
    }


    /**
     * 场馆修改密码  修改密码需要先传入之前的密码，然后在修改密码   新旧密码不能是重复的
     * @param
     * @return
     */
    @Transactional
    @GetMapping("/UpdateVenuePasswordParam")
    @ApiOperation("修改密码")
    public  Result UpdateVenuePasswordParam(String venuePass,@RequestHeader String token)throws Exception{
        String refreshToken = redisUtil.get(token);
        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("venueId").toString());
        UpdateVenuePasswordParam param = new UpdateVenuePasswordParam();
        param.setVenueId(userId);
        param.setVenuePass(venuePass);
        venueService.UpdateVenuePassword(param);
        return Result.getResult().setMsg("修改密码成功");
    }


    /**
     * 分页查询所有场馆
     * @param form
     * @return
     * @throws YogaException
     */
    @GetMapping("/pageAllVenue")
    @ApiOperation("分页查询所有场馆")
    public Result pageAllVenue(PageForm form) throws YogaException {
        Page<YVenue> page = venueService.pageAllVenue(BeanUtil.toBean(form, PageParam.class));
        return Result.newInstance(Page.class).setMsg("查询成功").setData(page).setCode(200);
    }


    /**
     *场馆发送登录短信
     * @param
     * @return
     */
    @ApiOperation(value = "场馆发送登录短信")
    @GetMapping("/LoginCodePhone")//发送登录短信
    public Result LoginCodePhone(@RequestParam("mobile") String mobile)throws Exception{
        venueService.LoginCodePhone(mobile);
        return Result.getResult().setMsg("发送登录短信成功").setCode(200);
    }
    /**
     *场馆手机号登录
     * @param
     * @return
     */
    @ApiOperation(value = "场馆手机号登录")
    @PostMapping("/codeLogin")
    public Result codeLogin(@RequestBody VenueCodeLoginForm form, HttpServletResponse response)throws Exception{
        VenueDto venueDto = venueService.codeLogin(BeanUtil.toBean(form, VenueCodeLoginParam.class));
        Map<String, Object> map = BeanUtil.beanToMap(venueDto);
        //生成短的token
        HashMap<String, Object> accessBody = new HashMap<>();
        //使用雪花算法生成随机的不同的短token，确保不重复
        String random = new Snowflake(1, 1).nextIdStr();
        accessBody.put("random",random);
        //生成短token
        String accessToken = JwtUtil.createToken(accessBody, 15);
        //生成长token
        String refreshToken = JwtUtil.createToken(map, 3*24*60);
        //将长的token保存到redis中
        redisUtil.set(accessToken,refreshToken,3*24*60*60);//3天有效时间
        //相应token前端
        response.setHeader("token",accessToken);
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.newInstance(VenueDto.class).setData(venueDto).setMsg("登录成功");
    }


    /**
     * 从token拿名字回去
     * @param token
     * @return
     * @throws YogaException
     */
    @GetMapping("/loadVenueName")
    @ApiOperation(value = "从token拿名字回去")
    public Result loadVenueName(@RequestHeader String token) throws YogaException {
        String refreshToken = redisUtil.get(token);
        Integer venueId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("venueId").toString());
        return Result.newInstance(null).setData(venueService.loadVenueName(String.valueOf(venueId))).setMsg("查询成功");
    }

    /**
     * 从token拿对象回去
     * @param token
     * @return
     * @throws YogaException
     */
    @GetMapping("/loadMyVenue")
    @ApiOperation(value = "从token拿对象回去")
    public Result<YVenue> loadMyVenue(@RequestHeader String token) throws YogaException {
        String refreshToken = redisUtil.get(token);
        Integer venueId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("venueId").toString());
        System.out.println(venueId+"控制层");
        return Result.newInstance(YVenue.class).setData(venueService.loadMyVenue(String.valueOf(venueId))).setMsg("查询成功");
    }


    /**
     * 根据id查找场馆信息
     * @param id
     * @return
     */
    @GetMapping("/byId/{id}")
    @ApiOperation("根据id查找场馆信息")
    public Result<YVenue> venueById(@PathVariable("id") Integer id)throws YogaException{
        if (id==null)throw new YogaException(500,"参数异常");
        YVenue venue = venueService.getById(id);
        return Result.newInstance(YVenue.class).setMsg("查询成功").setCode(200).setData(venue);
    }





}

